﻿using System;
using System.Linq;
using DayDayUp.Core.Domain.Users;
using DayDayUp.Service.Users;

namespace DayDayUp.Service.Securitys
{
    public class PermissionService:IPermissionService
    {
        private IUserService _userService;

        //public bool Authorize(PermissionRecord permission)
        //{
        //    return true;
        //}

        public PermissionService(IUserService userService)
        {
            _userService = userService;
        }

        public bool Authorize(PermissionRecord permissionRecord, string userId)
        {
            var customer = _userService.GetUserById(userId);

            return Authorize(permissionRecord.SystemName, customer);
        }

        private bool Authorize(string permissionRecordSystemName, User customer)
        {
            if (String.IsNullOrEmpty(permissionRecordSystemName))
                return false;

            var customerRoles = customer.UserRoles.Where(cr => cr.Active);
            foreach (var role in customerRoles)
                if (Authorize(permissionRecordSystemName, role))
                    //yes, we have such permission
                    return true;

            //no permission found
            return false;
        }


        protected virtual bool Authorize(string permissionRecordSystemName, UserRole customerRole)
        {
            if (String.IsNullOrEmpty(permissionRecordSystemName))
                return false;

            if (customerRole.PermissionRecords != null)
            {
                foreach (var permission1 in customerRole.PermissionRecords)
                {
                    if (permission1.SystemName.Equals(permissionRecordSystemName, StringComparison.InvariantCultureIgnoreCase))
                        return true;
                }
            }
           
            return false;

            //string key = string.Format(PERMISSIONS_ALLOWED_KEY, customerRole.Id, permissionRecordSystemName);
            //return _cacheManager.Get(key, () =>
            //{
            //    

            //    return false;
            //});
        }
    }
}